/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.common.utils.bean;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayatang.i18n.NoSuchMessageException;
import com.foreveross.bsl.common.utils.exception.ApplicationException;
import com.foreveross.bsl.common.utils.i18n.I18NResource;

/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-8-9
 *
 */
public class ExceptionUtils {
	
	private static Logger logger = LoggerFactory.getLogger(ExceptionUtils.class);
	
	 /**
	 * @param e
	 * @return
	 */
	public static String formatException(Throwable e){
		String message = null;
		
        if(e instanceof ApplicationException){
        	ApplicationException ex = (ApplicationException)e;
            message = getI18nMessage(ex.getCode(), ex.getMessage());
            if(StringUtils.isBlank(message)){
            	message = formatBaseException(e);
            }
//            return message + " [" + ex.getCode() + "]";
            return message;
        }
        
        message = formatBaseException(e);
	        
        message = message.replaceAll("\"", "'");
        return message;
	}

	/**
	 * @param e
	 * @return
	 */
	public static String formatBaseException(Throwable e) {
		String message;
		Throwable ourCause = e;
        while ((ourCause = e.getCause()) != null) {
            e = (Exception) ourCause;
        }
        
        message = e.getMessage();
        
        
        if(StringUtils.isBlank(message)) {
        	message = e.toString();
        }
		return message;
	}
	
	/** 添加异常码对应设置i18n国际化文件夹中/META-INF/i18n
	 * 
	 * @param code
	 * @param msg
	 * @return
	 */
	public static String getI18nMessage(String code, String msg){
		String message = null;
        I18NResource resource = I18NResource.getResource();
		if(StringUtils.isNotBlank(code)){
			try {
				message = resource.getMessage(code);
			} catch (NoSuchMessageException e) {
				if(StringUtils.isNotBlank(msg)){
					message = msg;
				}
				logger.error("the resource key not found");
			}
		}
		return message;
	}
	
	public static void main(String[] args) {
		ApplicationException a = new ApplicationException("employee.exist", "abc");
		Exception e = new Exception();
		System.out.println(ExceptionUtils.formatException(a));
		System.out.println(ExceptionUtils.formatException(e));
	}
}
